<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>检查括号是否匹配</title>
  </head>
  <body>
    <script>
      // a(b)c  true
      // a(bc   false
      // a[bc]d true
      // a([bc])d true
      // a(b[c)d] false
      function parse(source) {
        const stack = [];
        for (const c of source) {
          if (c === "(" || c === "[" || c === "{") {
            stack.push(c);
          }
          if (c === ")") {
            if (stack[stack.length - 1] === "(") {
              stack.pop();
            } else {
              return false;
            }
          }
          if (c === "}") {
            if (stack[stack.length - 1] === "{") {
              stack.pop();
            } else {
              return false;
            }
          }
          if (c === "]") {
            if (stack[stack.length - 1] === "[") {
              stack.pop();
            } else {
              return false;
            }
          }
        }
        if (stack.length === 0) {
          return true;
        } else {
          return false;
        }
      }
      console.log("Parse", parse("a[bc]d"));
    </script>
  </body>
</html>
